package com.tank.net.msg;

import com.tank.Bullet;
import com.tank.DirectionEnum;
import com.tank.GroupEnum;
import com.tank.TankFrame;

import java.io.*;
import java.util.UUID;

/**
 * @author CaoBaoYin
 * @since 21/11/4 16:27
 */
public class BulletNewMsg extends Msg {
    private int x, y;
    private DirectionEnum dir;
    private GroupEnum group;
    private UUID tankId;

    public BulletNewMsg() {
    }

    public BulletNewMsg(Bullet bullet, UUID tankId) {
        this.x = bullet.getX();
        this.y = bullet.getY();
        this.dir = bullet.getDir();
        this.group = bullet.getGroupEnum();
        this.tankId = tankId;
    }

    @Override
    public byte[] toBytes() {
        byte[] bytes = null;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             DataOutputStream dos = new DataOutputStream(baos);) {

            dos.writeInt(this.x);
            dos.writeInt(this.y);
            dos.writeInt(this.dir.ordinal());// 枚举 values 的 index 角标
            dos.writeInt(this.group.ordinal());
            dos.writeLong(this.tankId.getMostSignificantBits()); // 网络中没有人用字符串传输。会造成数据量大 这是128位的uuid，字符串128个字节，long只用了16个字节
            dos.writeLong(this.tankId.getLeastSignificantBits());
            dos.flush();

            bytes = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bytes;
    }

    @Override
    public void parse(byte[] bytes) {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             DataInputStream dis = new DataInputStream(bis)) {
            this.x = dis.readInt();
            this.y = dis.readInt();// 因为我们先写的x后写的y
            this.dir = DirectionEnum.values()[dis.readInt()];
            this.group = GroupEnum.values()[dis.readInt()];
            this.tankId = new UUID(dis.readLong(), dis.readLong());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void handle() {
        TankFrame tf = TankFrame.INSTANCE;
        if (this.tankId.equals(tf.getMainTank().getId())) {// 主站坦克发出的子弹不处理
            return;
        }

        tf.bulletList.add(new Bullet(this.x, this.y, this.dir, this.group, tf));
    }

    @Override
    public MsgTypeEnum getMsgType() {
        return MsgTypeEnum.BULLET_NEW;
    }

    @Override
    public String toString() {
        return "BulletNewMsg{" +
                "x=" + x +
                ", y=" + y +
                ", dir=" + dir +
                ", group=" + group +
                ", tankId=" + tankId +
                '}';
    }
}
